﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using CMTVision.Contracts;

namespace CMTVision.WidgetWeb.Services
{ 
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed),
    ServiceBehavior(IncludeExceptionDetailInFaults=true)]
    public class WidgetsService:IWidgetService
    {
        // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
        // To create an operation that returns XML,
        //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     and include the following line in the operation body:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
         

        // Add more operations here and mark them with [OperationContract]

       #region Implement IWidgetService

        public bool AddWidget(int type, int index,string columnId, long templateId)
        {
            bool result =false;
            using (CMTVision.Model.CMTWidgetsEntities entity = CMTVision.Common.EntitiesManager.LoadWidgetEntity())
            {
                var newWidget = new CMTVision.Model.Widget()
                {
                    ColumnID = columnId,
                    OrderNo = index
                };
                var widgetType = (from wt in entity.WidgetTypes where wt.ID == type  select wt).FirstOrDefault();
                var template = (from t in entity.Templates where t.ID == templateId select t).FirstOrDefault();
                var widgetContainerType = (from wct in entity.WidgetContainerTypes select wct).FirstOrDefault();
                if (widgetType != null && template != null && widgetContainerType!=null)
                {
                    newWidget.Template = template;
                    newWidget.WidgetType = widgetType;
                    newWidget.WidgetContainerType = widgetContainerType;
                    entity.AddToWidgets(newWidget);

                    var afterInsertWidgets = (from w in entity.Widgets
                                              where w.OrderNo >= index
                                                 && w.ColumnID == columnId
                                                 && w.Template.ID == templateId
                                                 && w.ID != newWidget.ID
                                              orderby w.OrderNo
                                              select w).ToList();
                    afterInsertWidgets.ForEach(w =>
                    {
                        w.OrderNo++;
                    });

                    result = entity.SaveChanges() > 0;       
                }
            }
            return result;
        }

        public bool MoveWidget(int id, string fromColumnId, int fromIndex, string toColumnId, int toIndex)
        {
            bool result = false;
            using (CMTVision.Model.CMTWidgetsEntities entity = CMTVision.Common.EntitiesManager.LoadWidgetEntity())
            {
                var widget = (from w in entity.Widgets.Include("Template") where w.ID == id && w.ColumnID == fromColumnId && w.OrderNo == fromIndex select w).FirstOrDefault();
                var allWillBeChangingWidgets = (from w in entity.Widgets
                                                  where ((w.OrderNo > fromIndex && w.ColumnID == fromColumnId && w.Template.ID == widget.Template.ID)
                                                        || (w.OrderNo >= toIndex && w.ColumnID == toColumnId && w.Template.ID == widget.Template.ID))
                                                     && w.ID != widget.ID
                                                  orderby w.OrderNo
                                                  select w).ToList(); 

                if (widget != null && widget.Template!=null)
                {
                    var fromWidgetList = (from w in allWillBeChangingWidgets
                                           where w.OrderNo > fromIndex
                                              && w.ColumnID == fromColumnId
                                              && w.Template.ID == widget.Template.ID
                                              && w.ID != widget.ID
                                           orderby w.OrderNo
                                           select w).ToList(); 
                    fromWidgetList.ForEach(w => w.OrderNo--);


                    var toWidgetList = (from w in allWillBeChangingWidgets
                                        where w.OrderNo >= toIndex
                                           && w.ColumnID == toColumnId
                                           && w.Template.ID == widget.Template.ID
                                           && w.ID != widget.ID
                                        orderby w.OrderNo
                                        select w).ToList();
                    toWidgetList.ForEach(w => w.OrderNo++);

                    widget.ColumnID = toColumnId;
                    widget.OrderNo = toIndex;

                    result = entity.SaveChanges() > 0;                    
                }
            }
            return result;
        }

        public bool RemoveWidget(int id)
        {
            bool result = false;
            using (CMTVision.Model.CMTWidgetsEntities entity = CMTVision.Common.EntitiesManager.LoadWidgetEntity())
            {
                var widget = (from w in entity.Widgets.Include("Template") where w.ID == id select w).FirstOrDefault();
                if (widget == null)
                {
                    result = true;
                }
                else
                {
                    var templateid = widget.Template.ID;
                    entity.DeleteObject(widget);
                    var afterThisWidgets = (from w in entity.Widgets
                                            where w.ColumnID == widget.ColumnID
                                                && w.Template.ID == templateid
                                                && w.OrderNo > widget.OrderNo
                                            select w).ToList();
                    afterThisWidgets.ForEach(w => { w.OrderNo--; });
                    result = entity.SaveChanges() > 0;
                }
            }
            return result;
        }

        #endregion


        public bool TestService(int id)
        {
            return id > 0;
        }
    }
}
